package cn.gdcp.FragmentAdapter;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.bumptech.glide.Glide;
import com.example.xinwenkehuduan.NewDetail;
import com.example.xinwenkehuduan.R;
import com.google.gson.Gson;

import java.util.List;

import cn.gdcp.Demo.Data;
import cn.gdcp.ViewHolder.NewsViewHolder;

public class NewsAdapter extends RecyclerView.Adapter<NewsViewHolder> {
    private List<Data> newsList;

    public NewsAdapter(List<Data> newsList) {
        this.newsList = newsList;
    }

    @NonNull
    @Override
    public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_news,viewGroup,false);

        NewsViewHolder newsViewHolder = new NewsViewHolder(view);

        return newsViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull NewsViewHolder newsViewHolder, final int i) {
        final Data data =  newsList.get(i);
        String imgUrl = data.getThumbnail_pic_s();
        if (imgUrl !=null && imgUrl.length()>0){
            Glide.with(newsViewHolder.ivImg.getContext()).load(imgUrl).into(newsViewHolder.ivImg);

        }

        newsViewHolder.tvTitle.setText(data.getTitle());
        newsViewHolder.tvAuthor.setText(data.getAuthor_name());
        newsViewHolder.tvDate.setText(data.getDate());

        newsViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),NewDetail.class);
                intent.putExtra("URL",data.getUrl());
                intent.putExtra("TITLE",data.getTitle());
                intent.putExtra("NEWSID",data.getUniquekey());
                intent.putExtra("NEWSJSON",new Gson().toJson(data));
                v.getContext().startActivity(intent);
            }
        });

    }

    @Override
    public int getItemCount() {
        return newsList.size();
    }


    public void changeDate(List<Data> newsList){
        this.newsList = newsList;
        notifyDataSetChanged();
    }
}
